package com.itheima.health.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {
    @Value("${alioss.endpoint}")
    private String endpoint;
    @Value("${alioss.accessKeyId}")
    private String accessKeyId;
    @Value("${alioss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${alioss.bucketName}")
    private String bucketName;
//    private String endpoint;
//    private String accessKeyId;
//    private String accessKeySecret;
//    private String bucketName;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        //获取源文件名字
        String originalFilename = file.getOriginalFilename();
        //取.后的格式  重新赋予文件名字
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(fileName);
        // 关闭ossClient
        ossClient.shutdown();
        return stringBuilder.toString();// 把上传到oss的路径返回
    }

    public List<String> listAllObjectKeysInBucket() throws OSSException {
        // 初始化OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 初始化对象键列表
        List<String> objectKeys = new ArrayList<>();

        // 创建列出对象的请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 使用迭代器遍历Bucket中的所有对象
        OSSObjectSummary objectSummary;
        ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
        do {
            for (OSSObjectSummary ossObjectSummary : objectListing.getObjectSummaries()) {
                objectKeys.add(ossObjectSummary.getKey());
            }
            // 如果有更多对象，则设置下一次请求的Marker
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated()); // 当isTruncated为false时，表示已经遍历完所有对象

        // 关闭OSS客户端
        ossClient.shutdown();

        // 返回包含所有对象键的列表
        return objectKeys;
    }

    public void deleteObject(String objectKey) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.deleteObject(bucketName, objectKey);

        // 关闭OSS客户端
        ossClient.shutdown();
    }

    /**
     * 阿里云批量删除 列表
     * @param ImgNameList
     */
    public void deleteByList(List<String> ImgNameList){
        //
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(ImgNameList).withEncodingType("url"));
    }
}